package com.gree.design_patterns.chain;

import com.gree.design_patterns.chain.filter.Filters;
import com.gree.design_patterns.chain.paramter.Responses;
import com.gree.design_patterns.chain.paramter.Requests;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: lyg
 * @Data: 2022/9/1
 * <p>
 * 责任链处理中心
 */
public class HandlerChain {

    private List<Filters> filterList = new ArrayList<>();

    int index = 0;

    /**
     * 提前添加处理器
     *
     * @param filters
     * @return
     */
    public HandlerChain addChain(Filters filters) {
        filterList.add(filters);
        return this;
    }

    public void doFilter(Requests requests, Responses responses) {
        // 执行到末尾, 不再往下走
        if (index == filterList.size()) {
            return;
        }
        // 获取需要执行的过滤器
        Filters filters = filterList.get(index);
        index++;
        filters.exec(requests, responses, this);

        // 2.如果不需要后置执行, 直接循环执行, 且无需传递HandlerChain
//        for (Filters filter : filterList) {
//            filter.exec(requests, responses, this);
//        }
    }
}
